<template>
  <div>
    <data-card
      v-loading="datacardLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/device-statistic/设备数网管数电站数统计'
        )
      "
      :data="dataCard"
      :items="dataCardItems"
      :tips="tips"
      @handleChange="initDataCard"
    />
    <EchartPanel
      v-loading="socketLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/device-statistic/插口数统计')
      "
      :title="socket"
      :timeUnit="'date'"
      @handleTableData="handleSocket"
      :echartsOption="lineBarOption"
    />
    <EchartPanel
      v-loading="stationLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/device-statistic/电站数统计')
      "
      :title="station"
      :timeUnit="'date'"
      @handleTableData="handleStation"
      :echartsOption="lineBarOption"
    />
    <EchartPanel
      v-loading="deviceLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/device-statistic/设备使用统计'
        )
      "
      :title="device"
      :defaultForm="deviceForm"
      :formItemsInline="deviceFormItems"
      :defaultFormItems="[
        'date',
        'address',
        'merchant',
        'station',
        'merchantCheckbox',
      ]"
      :timeUnit="'date'"
      @handleTableData="handleDevice"
      :echartsOption="barOption"
    />
    <EchartPanel
      v-loading="socketPerUserLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/device-statistic/人均端口数')
      "
      :title="socketPerUser"
      :timeUnit="'month'"
      @handleTableData="handleSocketPerUser"
      :echartsOption="barOption"
    />
  </div>
</template>
<script>
import EchartPanel from '@/components/EchartPanel'
import DataCard from './components/DataCard'
import * as visualizationFun from '@/utils/visualizationFun'
import _ from 'lodash'
import { constValue } from '@/config/echartsStyle'
import {
  getDeviceDataStatistics,
  getSocketCountGrow,
  getStationCountGrow,
  getDeviceUsedStatistics,
  getSocketPerUser,
} from '@/api/statistics'
import { lineBarOption, barOption } from './data/device'
export default {
  name: 'StatisticsDevice',
  components: { EchartPanel, DataCard },
  data() {
    return {
      datacardLoading: false,
      socketLoading: false,
      stationLoading: false,
      deviceLoading: false,
      socketPerUserLoading: false,
      socket: '插口数统计',
      station: '电站数统计',
      device: '设备使用统计',
      socketPerUser: '人均端口数统计',
      tips: [
        '数据统计截止前一天',
        '数据统计包含自营电站及下级代理电站',
        '网关：2G网关+4G网关设备数量',
        '智能插座: 智能插座设备数，不包含网关插座',
        'NB设备：自营NB设备+下级代理NB设备',
        '刷卡设备：自营电站刷卡设备+下级代理刷卡设备',
        '插口总数： 网关充电插口+NB充电插口+智能插座插口+刷卡设备插口',
      ],
      dataCard: {},
      dataCardItems: [
        {
          label: '电站数',
          formatter: (data) => {
            return (
              data.stationCount &&
              Number(data.stationCount.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '网关',
          formatter: (data) => {
            return (
              data.gatewayCount &&
              Number(data.gatewayCount.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '智能插座',
          formatter: (data) => {
            return (
              data.esimSocketCount &&
              Number(data.esimSocketCount.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: 'NB设备',
          formatter: (data) => {
            return (
              data.nbSocketCount &&
              Number(data.nbSocketCount.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '刷卡设备',
          formatter: (data) => {
            return (
              data.swipcardSocketCount &&
              Number(data.swipcardSocketCount.toFixed(2)).toLocaleString()
            )
          },
        },
      ],
      deviceFormItems: [
        {
          type: 'select',
          value: 'type',
          placeholder: '统计选择',
          clearable: true,
          options: [
            {
              label: '充电时长',
              value: 0,
              unit: 'h',
            },
            {
              label: '单口时长',
              value: 1,
              unit: 'h',
            },
            {
              label: '端口使用率',
              value: 2,
              unit: '%',
            },
          ],
        },
      ],
      deviceForm: {
        type: 0,
      },
      lineBarOption: lineBarOption,
      barOption: barOption,
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  created() {
    this.initDataCard(true)
  },
  methods: {
    initDataCard(val) {
      this.datacardLoading = true
      getDeviceDataStatistics({ containSubMch: val }).then(
        (res) => {
          this.dataCard = res
          this.datacardLoading = false
        },
        () => {
          this.datacardLoading = false
        }
      )
    },
    handleSocket(params, instance) {
      this.socketLoading = true
      getSocketCountGrow(params).then(
        (res) => {
          this.socketLoading = false
          let socketXAxis =
            res.allSocketCount && Object.keys(res.allSocketCount)
          visualizationFun.getXAxis(socketXAxis)
          let allSocketCount = _.values(res.allSocketCount)
          let addSocketCount = _.values(res.addSocketCount)
          let allSocketCountMax = visualizationFun.getMax(allSocketCount)
          let addSocketCountMax = visualizationFun.getMax(addSocketCount)
          let isHaveNegative = visualizationFun.getMin(
            _.concat(allSocketCount, addSocketCount)
          )
          instance.setOption({
            animation: true,
            xAxis: {
              data: socketXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '总插口（个）',
                show: true,
                max: allSocketCountMax,
                interval: allSocketCountMax / constValue.splitNumber,
                min: function () {
                  return isHaveNegative ? -allSocketCountMax : 0
                },
              },
              {
                name: '新增插口数(个)',
                show: true,
                max: addSocketCountMax,
                interval: addSocketCountMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [0, 130, 0, 60],
                },
                min: function () {
                  return isHaveNegative ? -addSocketCountMax : 0
                },
              },
            ],
            series: [
              {
                name: '总插口数',
                data: allSocketCount,
              },
              {
                name: '新增插口数',
                data: addSocketCount,
              },
            ],
          })
        },
        () => {
          this.socketLoading = false
        }
      )
    },
    handleStation(params, instance) {
      this.stationLoading = true
      getStationCountGrow(params).then(
        (res) => {
          this.stationLoading = false
          let socketXAxis =
            res.allStationCount && Object.keys(res.allStationCount)
          visualizationFun.getXAxis(socketXAxis)
          let allStationCount = _.values(res.allStationCount)
          let increaseStationCount = _.values(res.increaseStationCount)
          let allStationCountMax = visualizationFun.getMax(allStationCount)
          let increaseStationMax = visualizationFun.getMax(increaseStationCount)
          let isHaveNegative = visualizationFun.getMin(
            _.concat(allStationCount, increaseStationCount)
          )
          instance.setOption({
            animation: true,
            xAxis: {
              data: socketXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '总电站数（个）',
                show: true,
                max: allStationCountMax,
                interval: allStationCountMax / constValue.splitNumber,
                min: function () {
                  return isHaveNegative ? -allStationCountMax : 0
                },
              },
              {
                name: '新增电站数(个)',
                show: true,
                max: increaseStationMax,
                interval: increaseStationMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [0, 130, 0, 60],
                },
                min: function () {
                  return isHaveNegative ? -increaseStationMax : 0
                },
              },
            ],
            series: [
              {
                name: '总电站数',
                data: allStationCount,
              },
              {
                name: '新增电站数',
                data: increaseStationCount,
              },
            ],
          })
        },
        () => {
          this.stationLoading = false
        }
      )
    },
    handleDevice(params, instance) {
      this.deviceLoading = true
      getDeviceUsedStatistics(params).then(
        (res) => {
          this.deviceLoading = false
          let index = this.deviceFormItems.findIndex(
            (item) => item.value === 'type'
          )
          if (index < 0) return
          let optionItem = this.deviceFormItems[index].options.find(
            (item) => item.value === params.type
          )
          var deviceXAxis = _.keysIn(res.deviceUsedStatistic)
          visualizationFun.getXAxis(deviceXAxis)
          var deviceData = _.values(res.deviceUsedStatistic)
          if (params.type === 2) {
            //端口使用率,根据单口时长计算
            deviceData = _.map(deviceData, (item) => {
              return (item * 100).toFixed(2)
            })
          } else {
            deviceData = _.map(deviceData, (item) => {
              return (item / 60).toFixed(2)
            })
          }
          let deviceMax = visualizationFun.getMax(deviceData)
          instance.setOption({
            tooltip: {
              formatter: function (params) {
                return (
                  params.name +
                  '<br>' +
                  params.marker.replace(
                    /\[object Object\]/,
                    params.color.colorStops[0].color
                  ) +
                  params.seriesName +
                  ':' +
                  params.data +
                  optionItem.unit
                )
              },
            },
            xAxis: {
              data: deviceXAxis,
              show: true,
            },
            yAxis: [
              {
                name: `${optionItem.label}(${optionItem.unit})`,
                show: true,
                max: deviceMax,
                min: function (value) {
                  return value.min < 0 ? -deviceMax : 0
                },
                interval: deviceMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [0, 100, 0, 100],
                },
              },
            ],
            series: [
              {
                name: optionItem.label,
                type: 'bar',
                data: deviceData,
              },
            ],
            animation: true,
          })
        },
        () => {
          this.deviceLoading = false
        }
      )
    },
    handleSocketPerUser(params, instance) {
      this.socketPerUserLoading = true
      getSocketPerUser(params).then(
        (res) => {
          this.socketPerUserLoading = false
          let socketPerUserXAxis = _.keysIn(res.socketPerUser)
          visualizationFun.getMonthXAxis(socketPerUserXAxis)
          let socketPerUser = _.values(res.socketPerUser)
          socketPerUser = socketPerUser.map((item) => item.toFixed(4))
          let socketPerUserMax = visualizationFun.getMax(socketPerUser)
          instance.setOption({
            xAxis: {
              data: socketPerUserXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '人均端口数（个）',
                show: true,
                max: socketPerUserMax,
                interval: socketPerUserMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [0, 100, 0, 100],
                },
              },
            ],
            series: [
              {
                name: '人均端口数',
                type: 'bar',
                data: socketPerUser,
              },
            ],
            animation: true,
          })
        },
        () => {
          this.socketPerUserLoading = false
        }
      )
    },
  },
}
</script>
